package com.xiyou.week06.dp;

/**
 * 53. 最大子数组和
 *
 * @ClassName：MaxSubArray
 * @Author：西柚
 * @Date：2022/2/25 11:22 上午
 * @Versiion：1.0
 */
public class MaxSubArray {

    /**
     * 输入：nums = [-2,1,-3,4,-1,2,1,-5,4]
     * 输出：6
     * 解释：连续子数组 [4,-1,2,1] 的和最大，为 6 。
     *
     * @param nums
     * @return
     */
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int f[] = new int[n];
        f[0] = nums[0];
        for (int i = 1; i < n; i++) {
            f[i] = Math.max(f[i - 1], 0) + nums[i];
        }
        int ans = f[0];
        for (int i = 1; i < n; i++) {
            ans = Math.max(ans, f[i]);
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        MaxSubArray maxSubArray = new MaxSubArray();
        System.out.println(maxSubArray.maxSubArray(nums));
    }

}
